var express = require('express');
var router = express.Router();
var multiparty = require("multiparty");
var fs = require("fs");
var path = require("path");
var os = require("os");
var qr = require("qr-image");

/* GET home page. */
router.get("/file", function (req, res, next) {
	res.render("index", {title: "请选择需要上传到投影的文件", result: ""});
});

router.get("/", function (req, res, next) {
	res.render("qr");
});

router.get("/qr", function (req, res, next) {
	var ip;
	var interfaces = os.networkInterfaces();
	for (var dev in interfaces) {
		var interface = interfaces[dev];
		for (var i = 0; i < interface.length; i++) {
			var alias = interface[i];
			if (alias.family === "IPv4" && alias.address !== "127.0.0.1" && !alias.internal) {
				ip = alias.address;
				break;
			}
		}
	}
	console.log("found ip: " + ip);
	var img = qr.image("http://" + ip + ":3000/file");
	try {
		res.writeHead(200, {'Content-Type': 'image/png'});
		img.pipe(res);
		// res.render("qr", {src: img});
	} catch (e) {
		res.render("error", {message: "二维码生成失败", error: e});
	}
});

router.post("/upload", function (req, res, next) {
	var form = new multiparty.Form();
	form.encoding = "utf-8";
	form.uploadDir = "upload";
	form.parse(req, function (err, fields, files) {
		if (err) {
			res.render("error", {message: "上传文件失败", error: err});
			return;
		}

		var file = files.upload[0];
		var oldPathname = file.path;
		var newPathname = form.uploadDir + path.sep + file.originalFilename;
		fs.rename(oldPathname, newPathname, function () {
			res.render("index", {title: "请选择需要上传到投影的文件", result: "上传文件成功 [" + file.originalFilename + "]"});
		});
	});
});

module.exports = router;
